package com.job.core.thread;

import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.job.core.biz.AdminBiz;
import com.job.core.biz.model.HandleCallBackParam;
import com.job.core.biz.model.ReturnModel;
import com.job.core.rpc.NetComClientProxy;
/**
 * 
 * @Title: TriggerCallBackThread.java
 * @Package: com.job.core.thread
 * @Description:执行器执行线程回调函数
 * @author: sunwei
 * @date: 2017年5月15日 上午10:33:31
 * @version: V1.0
 */
public class TriggerCallBackThread {
    private static Logger logger = LoggerFactory.getLogger(TriggerCallBackThread.class);
    private static TriggerCallBackThread instance = new TriggerCallBackThread();
    public static TriggerCallBackThread getInstance(){
        return instance;
    }
    private LinkedBlockingQueue<HandleCallBackParam> callbackQueue=new LinkedBlockingQueue<HandleCallBackParam>();
    private Thread triggerCallbackThread;
    private boolean toStop=false;
    public void start(){
	triggerCallbackThread=new Thread(new Runnable() {
	    @Override
	    public void run() {
		if(!toStop){//如果没有停止
		    try {
			HandleCallBackParam backParam=callbackQueue.take();
			if(null!=backParam){
			    for (String address : backParam.getLogAddress()) {
				try {
				    // callback
				    AdminBiz adminBiz = (AdminBiz) new NetComClientProxy( AdminBiz.class, address).getObject();
				    ReturnModel<String> callbackResult = adminBiz.callback(backParam);
				    logger.info( ">>>>>>>>>>> job callback , CallbackParam:{}, callbackResult:{}", new Object[] { backParam.toString(),callbackResult.toString() });
				    if (ReturnModel.SUCCESS_CODE == callbackResult
					    .getCode()) {
					break;
				    }
				} catch (Exception e) {
				    logger.error(
					    ">>>>>>>>>>> xxl-job TriggerCallbackThread Exception:",
					    e);
				}
			    }
			}
		    } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		}
	    }
	});
	 triggerCallbackThread.setDaemon(true);
	 triggerCallbackThread.start();
    }
    public void toStop(){
        toStop = true;
    }
    /**
     * 
     * @Title: pushCallBack
     * @Description:job执行返回信息放入队列
     * @author:sunwei
     * @createTime:2017年5月15日上午11:01:04
     * @param callback
     */
    public static void pushCallBack(HandleCallBackParam callback){
        getInstance().callbackQueue.add(callback);
        logger.debug(">>>>>>>>>>>job, push callback request, logId:{}", callback.getLogId());
    }

    
}
